<template>
    <div class="add-equipment">
        <div class="form-item form-item-style1">
            <div class="label-title">
                <label>项目名称</label>
            </div>
            <div class="equipment-right-select"
                 @click="selectType">
                <span>{{checkcompany.Name?checkcompany.Name:'请选择'}}</span>
                <i class="iconfont icon-jinru rightmsg"></i>
            </div>
        </div>
        <div class="form-item form-item-style1">
            <div class="label-title">
                <label>设备类型</label>
                <i class="iconfont icon-required"></i>
            </div>
            <group v-if="equipmentType[0].length">
                <popup-picker :data="equipmentType"
                              @on-change="changeEquipmentType"
                              placeholder='请选择'
                              v-model="equipmentTypeVal"></popup-picker>
            </group>
        </div>
        <div class="form-item form-item-style1">
            <div class="label-title">
                <label>自编号</label>
                <i class="iconfont icon-required"></i>
            </div>
            <group v-if="generateNo[0].length || generateNoVal[0]">
                <popup-picker :data="generateNo"
                              placeholder='请选择'
                              v-model="generateNoVal"></popup-picker>
            </group>
            <div v-else>
                <p>暂无数据</p>
            </div>
        </div>
        <div class="form-item form-item-style1">
            <div class="label-title">
                <label>是否自有设备</label>
                <i class="iconfont icon-required"></i>
            </div>
            <group>
                <popup-picker :data="ownEquipment"
                              placeholder='请选择'
                              v-model="ownEquipmentVal"></popup-picker>
            </group>
        </div>
        <div class="form-item form-item-style1">
            <div class="label-title">
                <label>进场日期</label>
                <i class="iconfont icon-required"></i>
            </div>
            <group>
                <datetime v-model="formData.EntryDate"></datetime>
            </group>
        </div>
        <div class="form-item form-item-style1">
            <div class="label-title">
                <label>验收日期</label>
                <i class="iconfont icon-required"></i>
            </div>
            <group>
                <datetime v-model="formData.CheckDate"></datetime>
            </group>
        </div>
        <div class="form-item form-item-style2">
            <div class="label-title">
                <label>参加验收人员</label>
                <i class="iconfont icon-required"></i>
            </div>
            <div>
                <textarea maxlength="200"
                          placeholder="请输入验收人员名字"
                          v-model="formData.CheckPerSonnel"></textarea>
            </div>
        </div>
        <div class="form-item form-item-style2"
             v-if="equipmentTypeVal[0] == '其他'">
            <div class="label-title">
                <label>验收内容</label>
                <i class="iconfont icon-required"></i>
            </div>
            <div>
                <textarea maxlength="200"
                          placeholder="请输入验收内容"
                          v-model="formData.AcceptanceContent"></textarea>
            </div>
        </div>
        <div v-for="(items,key) in acceptanceItems"
             :key="key">
            <div class="cut-off-rule"></div>
            <div class="form-section">
                <h3 data-v-d3024438="">{{key | filterTitle}}</h3>
                <div class="form-item form-item-style1"
                     v-for="(item,index) in items"
                     :key="index">
                    <div class="label-title label-title1">
                        <label>{{item.AcceptanceItemName}}</label>
                        <i class="iconfont icon-required"></i>
                    </div>
                    <div class="select-section">
                        <div :class="{'active':item.AcceptanceItemResult == '是'}"
                             @click="changeItemResult(item,'是')">
                            是
                        </div>
                        <div :class="{'active':item.AcceptanceItemResult == '否'}"
                             @click="changeItemResult(item,'否')">
                            否
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="cut-off-rule"></div>
        <div class="form-section">
            <h3>
                验收图片
            </h3>
            <div class="form-item form-item-style2">
                <div class="label-title space-between">
                    <div class="space-between">
                        <label>照片</label>
                        <i class="iconfont icon-required"></i>
                    </div>
                    <span>当前共{{YSuploadLength}}张</span>
                </div>
                <div class="upload-wrap">
                    <upload :ImagesFiles="ImagesFiles"
                            @setFormData="setYSFormData"></upload>
                </div>
            </div>
            <div class="form-item form-item-style1">
                <div class="label-title">
                    <label>验证结论</label>
                    <i class="iconfont icon-required"></i>
                </div>
                <div class="select-section">
                    <div :class="{'active': formData.IsResults == '1'}"
                         @click="formData.IsResults = '1'">
                        合格
                    </div>
                    <div :class="{'active': formData.IsResults == '0'}"
                         @click="formData.IsResults = '0'">
                        不合格
                    </div>
                </div>
            </div>
            <div class="form-item form-item-style2">
                <div class="label-title">
                    <label>验收意见</label>
                    <i class="iconfont icon-required"></i>
                </div>
                <div>
                    <textarea maxlength="200"
                              placeholder="请输入验收意见"
                              v-model="formData.AcceptanceConclusion"></textarea>
                </div>
            </div>
            <div class="btns">
                <button @click="handleSubmit('save')">保存</button>
                <button class="green"
                        @click="handleSubmit('submit')">提交</button>
            </div>
        </div>
        <myMenu></myMenu>
    </div>
</template>
<script>
import myMenu from '@/commonComponents/menu'
import upload from '@/commonComponents/upload/index'
export default {
    name: 'addEquipment',
    data () {
        return {
            YSFormData: '',
            YSuploadLength: '',
            checkcompany: {
            }, //  单位名称
            userInfo: {},
            equipmentTypeData: '',
            equipmentType: [[]], //  设备类型
            equipmentTypeVal: [], // 选中设备类型
            ownEquipment: [['是', '否']], // 是否自有设备
            ownEquipmentVal: ['是'],
            generateNo: [[]], // 自编号
            generateNoVal: [],
            acceptanceItems: {},
            ImagesFiles: [],
            formData: {
                ID: '',
                EntryDate: '', // 进场时间
                CheckDate: '', // 验收时间
                IsResults: '0', // 验收结果1：合格 0不合格
                AcceptanceContent: '', // 验收内容（设备类型选择其他时）
                AcceptanceConclusion: '', // 验收意见
                CheckPerSonnel: '', // 验收人员
                EquipmentTypeNo: '', // 设备类型编号
                ItemList: []
            }
        }
    },
    components: {
        upload,
        myMenu
    },
    filters: {
        filterTitle: function (val) {
            let title
            switch (val) {
                case 'BasicDataList':
                    title = '基本资料'
                    break
                case 'StructureList':
                    title = '塔吊结构'
                    break
                case 'RotationSystemList':
                    title = '绳轮转动系统'
                    break
                case 'AHookList':
                    title = '吊钩'
                    break
                case 'LimitInsuRanceList':
                    title = '限位保险'
                    break
                case 'DriveSystemList':
                    title = '机构传动系统'
                    break
                case 'PulleyList':
                    title = '卷筒滑轮'
                    break
                case 'ElectricalSystemList':
                    title = '司机室及电气系统'
                    break
                case 'BasicsList':
                    title = '基础'
                    break
                case 'SafeguardList':
                    title = '设备安全保护装置'
                    break
                case 'GearRackList':
                    title = '齿轮齿条'
                    break
                case 'GuideWayFrameList':
                    title = '导轨架'
                    break
                case 'WireropeList':
                    title = '钢丝绳与配重'
                    break
                case 'BoltList':
                    title = '螺栓及配件'
                    break
                case 'DriverElectricalSystemList':
                    title = '司机位与电气系统'
                    break
                case 'AppearanceCheckList':
                    title = '外观检查'
                    break
                case 'DriversCheckList':
                    title = '司机室检查'
                    break
                case 'TrackList':
                    title = '轨道检查'
                    break
                case 'SlingCheckList':
                    title = '吊具检查'
                    break
                case 'WireropeCheckList':
                    title = '钢丝绳检查'
                    break
                case 'PulleyCheckList':
                    title = '滑轮检查'
                    break
                case 'ElectricalSystemCheckList':
                    title = '电气系统检查'
                    break
                case 'HydraulicSystemCheckList':
                    title = '液压系统检查'
                    break
                case 'SafeguardCheckList':
                    title = '安全防护装置检查'
                    break
                case 'AppearanceChecList':
                    title = '外观检查'
                    break
                case 'SafetySystemList':
                    title = '安全系统'
                    break
                default:
                    title = ''
                    break
            }
            return title
        }
    },
    created () {
        this.userInfo = JSON.parse(localStorage.getItem('userInfo')) || {}
        this.checkcompany = this.$store.state.checkcompany && JSON.stringify(this.$store.state.checkcompany) !== '{}' ? JSON.parse(JSON.stringify(this.$store.state.checkcompany)) : {
            Name: this.userInfo.deptname,
            Id: this.userInfo.deptid
        }
        this.formData.ID = this.$route.query.id
        this.getEquipment()
    },
    methods: {
        setYSFormData (formData, uploadLength) {
            this.YSFormData = formData
            this.YSuploadLength = uploadLength
        },
        selectType () {
            this.$router.push({ path: '/testing/lookcompany' })
        },
        getSiteAcceptanceDetails () {
            let params = {
                'allowPaging': false,
                'business': 'getSiteAcceptanceDetails',
                'data': {
                    id: this.formData.ID
                },
                'pageIndex': 0,
                'pageSize': 20,
                'tokenId': '',
                'userId': this.userInfo.userid
            }
            this.$axiosAjax.getConfigJson(params).then((res) => {
                if (res.data.code === 0) {
                    let data = res.data.data
                    for (const key in data) {
                        if (data[key] instanceof Array && key !== 'ImagesFiles') {
                            this.acceptanceItems[key] = data[key]
                        } else if (!(data[key] instanceof Array)) {
                            this.formData[key] = data[key]
                        }
                    }
                    this.equipmentTypeVal[0] = res.data.data.EquipmentTypeName
                    res.data.data.ImagesFiles.forEach(item => {
                        this.ImagesFiles.push({
                            url: item
                        })
                    })

                    this.getGenerateNo(res.data.data.EquipmentNo)
                    this.$forceUpdate()
                }
            }).catch(() => {

            }).finally(() => {
                this.$vux.loading.hide()
            })
        },
        getEquipment () { // 获取设备类型
            let params = {
                'allowPaging': false,
                'business': 'GetEquipment',
                'data': {},
                'pageIndex': 0,
                'pageSize': 20,
                'tokenId': '',
                'userId': this.userInfo.userid
            }
            this.$axiosAjax.getConfigJson(params).then((res) => {
                if (res.data.code === 0) {
                    this.equipmentTypeData = res.data.data
                    this.equipmentTypeData.forEach((item, index) => {
                        this.equipmentType[0][index] = item.EquipmentTypeName
                    })
                    if (this.formData.ID) {
                        this.$vux.loading.show({
                            text: '加载中...'
                        })
                        this.getSiteAcceptanceDetails()
                    } else {
                        this.$forceUpdate()
                    }
                }
            }).catch(() => {

            }).finally(() => {
                this.$vux.loading.hide()
            })
        },
        changeEquipmentType (equipmentTypeVal) {
            for (let i = 0; i < this.equipmentTypeData.length; i++) {
                if (equipmentTypeVal[0] == this.equipmentTypeData[i].EquipmentTypeName) {
                    this.formData.EquipmentTypeNo = this.equipmentTypeData[i].EquipmentTypeNo
                    break
                }
            }
            this.getGenerateNo()
            this.getAddAcceptanceItem()
        },
        getGenerateNo (EquipmentNo) {
            let params = {
                'allowPaging': false,
                'business': 'GetGenerateNo',
                'data': {
                    ProjectId: this.checkcompany.Id,
                    EquipmentTypeNo: this.formData.EquipmentTypeNo
                },
                'pageIndex': 0,
                'pageSize': 20,
                'tokenId': '',
                'userId': this.userInfo.userid
            }

            this.$axiosAjax.getConfigJson(params).then((res) => {
                if (res.data.code === 0) {
                    this.generateNo[0] = []
                    this.$nextTick(() => {
                        this.generateNo[0] = res.data.data
                        this.generateNoVal = EquipmentNo ? [EquipmentNo] : []
                        this.$forceUpdate()
                    })
                }
            }).catch(() => {

            }).finally(() => {
                this.$vux.loading.hide()
            })
        },
        getAddAcceptanceItem () {
            let params = {
                'allowPaging': false,
                'business': 'GetAddAcceptanceItem',
                'data': {
                    EquipmentTypeNo: this.formData.EquipmentTypeNo,
                    tokenId: ''
                },
                'pageIndex': 0,
                'pageSize': 20,
                'tokenId': '',
                'userId': this.userInfo.userid
            }
            this.$axiosAjax.getConfigJson(params).then((res) => {
                if (res.data.code === 0) {
                    this.acceptanceItems = res.data.data
                    for (const key in this.acceptanceItems) {
                        for (let i = 0; i < this.acceptanceItems[key].length; i++) {
                            this.acceptanceItems[key][i].AcceptanceItemResult = this.acceptanceItems[key][i].AcceptanceItemResult || '是'
                        }
                    }
                }
            }).catch(() => {

            }).finally(() => {
                this.$vux.loading.hide()
            })
        },
        handleSubmit (method) {
            let params = {
                business: 'EquipmentSiteAcceptance',
                data: this.formData,
                method: method,
                userId: this.userInfo.userid
            }
            this.formData.ImagesFiles = []
            this.ImagesFiles.forEach(item => {
                this.formData.ImagesFiles.push(item.url)
            })
            params.data.ProjectId = this.checkcompany.Id
            params.data.EquipmentNo = this.generateNoVal[0]
            params.data.IsSelfEquipment = this.ownEquipmentVal[0]
            if (!params.data.EquipmentTypeNo) {
                this.$vux.toast.text('请选择设备类型')
                return false
            } else if (!params.data.EquipmentNo) {
                this.$vux.toast.text('请选择自编号')
                return false
            } else if (!params.data.EntryDate) {
                this.$vux.toast.text('请选择进场日期')
                return false
            } else if (!params.data.CheckDate) {
                this.$vux.toast.text('请选择验收日期')
                return false
            } else if (!params.data.CheckPerSonnel) {
                this.$vux.toast.text('请输入验收人员')
                return false
            } else if (this.equipmentTypeVal[0] == '其他' && !params.data.AcceptanceContent) {
                this.$vux.toast.text('请输入验收内容')
                return false
            } else if (this.YSuploadLength == 0 && this.ImagesFiles.length == 0) {
                this.$vux.toast.text('请上传照片')
                return false
            } else if (!params.data.AcceptanceConclusion) {
                this.$vux.toast.text('请输入验收意见')
                return false
            } else if (new Date(params.data.EntryDate).getTime() > new Date(params.data.CheckDate).getTime()) {
                this.$vux.toast.text('进场日期不能大于验收日期')
                return false
            }
            for (const key in this.acceptanceItems) {
                params.data.ItemList = params.data.ItemList.concat(this.acceptanceItems[key])
            }
            let text = ''
            if (method === 'submit') {
                text = '正在提交'
            } else {
                text = '正在保存'
            }
            this.$vux.loading.show({
                text: `${text}...`
            })
            this.$axiosAjax.getConfigJson(params, this.YSFormData).then((res) => {
                if (res.data.code === 0) {
                    if (method == 'submit') {
                        this.$vux.toast.text('提交成功')
                    } else {
                        this.$vux.toast.text('保存成功')
                    }
                    this.$router.replace('/equipmentEnterManage')
                }
            }).catch(() => {

            }).finally(() => {
                this.$vux.loading.hide()
            })
        },
        changeItemResult (item, result) {
            item.AcceptanceItemResult = result
            this.$forceUpdate()
        }
    }
}
</script>
<style lang="less" scoped>
.select-section {
    display: flex;
}
.select-section div {
    padding-left: 26px;
    background: url(../../../../static/images/select.png) no-repeat left center;
    background-size: 17px 17px;
}
.select-section div:first-child {
    margin-right: 58px;
}
.select-section .active {
    background: url(../../../../static/images/selected.png) no-repeat left
        center;
    background-size: 17px 17px;
}
.add-equipment .label-title1 {
    width: 168px;
    line-height: 18px;
}
.right-select {
    display: flex;
    align-items: center;
}
.right-select span {
    font-size: 13px;
    color: #666;
    height: 20px;
    overflow: hidden;
    width: 186px;
    position: relative;
    line-height: 20px;
    text-align: right;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.right-select .icon-jinru {
    color: #c8c8cd;
    margin-right: -3px;
}
</style>
